package com.lam.mall.controller;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.base.domain.tree.TreeNode;
import com.lam.common.base.domain.tree.TreeUtil;
import com.lam.common.base.page.TableData;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.constant.CommonConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.BusinessException;
import com.lam.common.utils.JsonUtil;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.common.validate.model.ValidOperType;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.mall.common.constant.MallConstant;
import com.lam.mall.entity.Category;
import com.lam.mall.param.CategoryParam;
import com.lam.mall.service.CategoryService;

/**
 * 产品类目Controller
 * 
 * @author admin
 * @date 2023-04-20
 */
@Log(title = "产品类目")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/mall/category")
public class CategoryController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询产品类目列表
     */
    @Log(oper="列表查询")
    @DictAutoTransfer(deep = true)
    @PreAuthorize("@ss.hasPm('mall:category:list')")
    @GetMapping("/list")
    public Result list(CategoryParam param) {
    
    	param.setShopId(TokenUtils.getLoginUserShopId());
        List<Category> list = categoryService.selectList(param);
        list = TreeUtil.buildTree(list);
        return Result.ok(new TableData(list, list.size()));
    }

    /**
     * 产品类目下拉树列表
     */
    @Log(oper="产品类目下拉树列表")
    @PreAuthorize("@ss.hasPm('mall:category:list')")
    @GetMapping("/treeselect")
    public Result treeselect(CategoryParam param) {
    
    	param.setShopId(TokenUtils.getLoginUserShopId());
    	//PageHelper.orderBy("parent_id, sort_no");
        List<Category> list = categoryService.selectList(param);
        List<TreeNode> treeNodeList = JsonUtil.toJavaList(list, TreeNode.class, "id", "parentId", "name=>title", "sortNo");
        return Result.ok(TreeUtil.buildTree(treeNodeList, CommonConstant.TOP_PARENT_ID));
    }

    /**
     * 获取产品类目详细信息
     */
    @DictAutoTransfer
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('mall:category:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
        return Result.ok(categoryService.selectById(id));
    }

    /**
     * 新增产品类目
     */
    @PreAuthorize("@ss.hasPm('mall:category:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody Category category) {
    
    	category.setShopId(TokenUtils.getLoginUserShopId());
    	
        ValidateUtil.validUnique(category, ValidOperType.ADD, MallConstant.UNIQUE_CATEGORY_NAME, "产品类目名称已存在！");
        return toAjax(categoryService.insert(category));
    }

    /**
     * 修改产品类目
     */
    @PreAuthorize("@ss.hasPm('mall:category:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody Category category) {
    
    	category.setShopId(TokenUtils.getLoginUserShopId());
    	
        ValidateUtil.validUnique(category, ValidOperType.UPDATE, MallConstant.UNIQUE_CATEGORY_NAME, "产品类目名称已存在！");
        
        Category categoryDb = categoryService.selectById(category.getId());
		// 如果从下线改成正常，则需要判断上级的状态
		if (Objects.equals(categoryDb.getStatus(),0) && Objects.equals(category.getStatus(),1) && !Objects.equals(category.getParentId(),0L)){
			Category parentCategory = categoryService.selectById(category.getParentId());
			if(Objects.isNull(parentCategory) || Objects.equals(parentCategory.getStatus(),0)){
				// 修改失败，上级分类不存在或者不为正常状态
				throw new BusinessException("上级分类不存在或已下线");
			}
		}
		
        return toAjax(categoryService.update(category));
    }

    /**
     * 删除产品类目
     */
    @PreAuthorize("@ss.hasPm('mall:category:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
        return toAjax(categoryService.deleteById(id));
    }

}
